package com.fresh.system.controller;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fresh.common.ResponseResult;
import com.fresh.entity.User;
import com.fresh.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * @author Wx
 * @Date:2023/08/09/10:27
 * @Description:
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Value("${jwt.data.secretKey}")
    private String secretKey;
    @PostMapping("add")
    public ResponseResult<Void> add(@RequestBody User user){
        userService.save(user);
        return new ResponseResult<>(200,"ok",null);
    }
    /**
     * 判断账号密码生成令牌
     * */
//    @GetMapping("login")
//    public ResponseResult<Void>login(@RequestBody User user, HttpServletResponse response){
//        QueryWrapper<User> queryWrapper=new QueryWrapper<>(user);
//        User user1=userService.getOne(queryWrapper);
//        if (user.getPassword().equals(user1.getPassword())){
//            String token = JWT.create()
//                    .setPayload("id",String.valueOf(user1.getId()))
//                    .setPayload("account", user.getAccount())
//                    .setKey(secretKey.getBytes())
//                    .sign();
//            response.setHeader("authorization", token);
//            return new ResponseResult<>(200,"登录成功",null);
//        }else {
//            return new ResponseResult<>(500,"账号或密码错误",null);
//        }
//    }
    @GetMapping("getById")
    public ResponseResult<User>getById(Integer id){
        return ResponseResult.success(userService.getById(id));
    }

    /**
     * 令牌认证
     * */
    @RequestMapping("verify")
    public ResponseResult<String>verify( String authorization){
        JWT jwt= JWT.of(authorization);
        String id=(String) jwt.getPayload("id");
        boolean verify= JWTUtil.verify(authorization,secretKey.getBytes());
        if (verify) {
            return new ResponseResult<String>(200,"ok123",id);
        }
        return new ResponseResult<String>(500,"fall",null);
    }

}
